﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    dbName=DB_FILE;
    table=TD_TABLE;
    addItem=nullptr;

    //不接受拖放
    ui->listWidget->setAcceptDrops(false);

    //图标模式
    ui->listWidget->setViewMode(QListWidget::IconMode);

    //换行显示
    ui->listWidget->setLayoutMode(QListWidget::Batched);

    //尺寸变化时自动调整尺寸
    ui->listWidget->setResizeMode(QListWidget::Adjust);
    ui->listWidget->setIconSize(QSize(96,96));

    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    detectDB();
    createMenu();
}

Widget::~Widget()
{
    if(db.isOpen())
        db.close();

    delete ui;
}

bool Widget::db_try()
{
    if(!db.isOpen())
    {
        if(!db.open())
        {
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("无法打开本地数据库"));
            return false;
        }
        else
            return true;
    }
    else
        return true;
}

void Widget::contextMenuEvent(QContextMenuEvent *)
{
    menu->exec(QCursor::pos());
}

void Widget::createMenu()
{
    menu=new QMenu(this);
    menu->addAction(QStringLiteral("添加..."),this,&Widget::newItem);
}

void Widget::detectDB()
{
    db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbName);

    if(!QFile::exists(dbName))
    {
        if(db.open())
        {
            QSqlQuery query;
            QString sql=QString(CREATE_CONE).arg(table);
            if(!query.exec(sql))
            {
                QMessageBox::warning(this,QStringLiteral("异常情况"),
                                     QStringLiteral("无法创建本地数据库"));
                qDebug() << query.lastError().text();
            }
        }
        else
            QMessageBox::warning(this,QStringLiteral("异常情况"),
                                 QStringLiteral("无法打开本地数据库"));
    }
    loadView();
}

void Widget::loadView()
{
    if(!db_try())
        return;

    if(ui->listWidget->count() > 0)
        ui->listWidget->clear();

    QSqlQuery query;
    query.exec(QString("select label,addition from %1").arg(table));
    while (query.next()) {
        QString label=query.value("label").toString();
        QString addition=query.value("addition").toString();
        QString pic=PRE_PIC + addition;

        QListWidgetItem *newItem = new QListWidgetItem(label);
        newItem->setIcon(QIcon(pic));
        ui->listWidget->addItem(newItem);
    }

    QStringList categories;
    query.exec(QString("select category from %1 group by category").arg(table));
    while (query.next()) {
        categories.append(query.value("category").toString());
    }
    if(!categories.isEmpty())
        listModel->setStringList(categories);

    db.close();
}

void Widget::newItem()
{
    if(addItem==nullptr)
    {
        addItem=new AddItem(this);
        connect(addItem,&AddItem::sendItem,this,&Widget::receiveItem);
  //      connect(addItem,&AddItem::accepted,this,&Widget::loadView);
    }
    addItem->show();
}

void Widget::receiveItem(const Item &item)
{
    if(!db_try())
        return;

    QSqlQuery query;
    query.prepare(QString("insert into %1 (category,label,detail,addition) values (?,?,?,?)").arg(table));
    query.addBindValue(item.category);
    query.addBindValue(item.label);
    query.addBindValue(item.detail);
    query.addBindValue(item.addition);

    if(!query.exec())
    {
        QMessageBox::warning(this,QStringLiteral("异常情况"),
                             QStringLiteral("数据提交失败！"));
        qDebug() << query.lastError().text();
        return;
    }

    loadView();
}

void Widget::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    if(!db_try())
        return;

    QString label=item->text();
    QSqlQuery query;
    QString sql=QString("select category,detail from %1 where label ='%2'").arg(table).arg(label);
    query.exec(sql);
    if(query.next())
    {
        QString category=query.value("category").toString();
        ui->label->setText(QStringLiteral("【") + category + QStringLiteral("】 ")  + label);
        ui->detail->setPlainText(query.value("detail").toString());
    }
    db.close();
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        if(!db_try())
            return;

        if(ui->listWidget->count() > 0)
            ui->listWidget->clear();

        QString category=listModel->data(index).toString();
        QSqlQuery query;
        query.exec(QString("select label,addition from %1 where category='%2'").arg(table).arg(category));
        while (query.next()) {
            QString label=query.value("label").toString();
            QString addition=query.value("addition").toString();
            QString pic=PRE_PIC + addition;

            QListWidgetItem *newItem = new QListWidgetItem(label);
            newItem->setIcon(QIcon(pic));
            ui->listWidget->addItem(newItem);
        }
        db.close();
    }
}
